package com.incar.chuxing.utils;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.provider.Settings;
import android.support.multidex.MultiDex;

import com.alibaba.sdk.android.media.utils.Md5Utils;
import com.baidu.mapapi.SDKInitializer;
import com.incar.chuxing.activity.MainActivity;
import com.incar.chuxing.ble.ViseBluetooth;
import com.tencent.bugly.Bugly;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.utils.Log;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Build.VERSION.SDK;


/**
 * Created by Michael Pi on 2016/10/9.
 */
public class MyApplication extends Application {
    {
        PlatformConfig.setWeixin("wx27be95a6499eb5f1", "a6e76030ba09ccf23ae5187360f149b4");
        PlatformConfig.setQQZone("1106533170", "YAZNwjjCLN99Yd4J");
        Config.DEBUG = true;
    }


    private VerControlUtils verControl;
    private String uid;
    private String token;
    private String sign;
    private String appVersion;
    private String areaCode;
    private String adCode;
    private String[] curPosition = new String[2];
    private int tripMode;  //当前选择的出行方式 1电车 2单车
    private int tripAvai;  //该城市可用的出行方式
    private String imageUrl;
    private String hotLine;
    private String orderId;
    public byte[] btToken;//蓝牙token
    private Context mContext = this;
    private static MyApplication instance;


    public static Application getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        Bugly.init(mContext, "79f2acc4ff", false);//bugly初始化
        SDKInitializer.initialize(mContext); //百度地图初始化
        ViseBluetooth.getInstance().init(this);
        UMShareAPI.get(mContext); //友盟初始化
        initUmeng();

        MobclickAgent.setScenarioType(mContext, MobclickAgent.EScenarioType.E_UM_NORMAL);
        MobclickAgent.openActivityDurationTrack(false);
        verControl = new VerControlUtils(mContext);
        appVersion = verControl.getVersionName();

    }

    private void initUmeng() {
        //接收友盟消息
        final PushAgent mPushAgent = PushAgent.getInstance(mContext);
        mPushAgent.setDebugMode(true);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEVICE_TOKEN, deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });


        //接收友盟通知，无需点击通知，即可接收自定义参数
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public Notification getNotification(final Context context, final UMessage msg) {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
                return super.getNotification(context, msg);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        //接收友盟通知，需点击通知，即可接收自定义参数
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void launchApp(Context context, UMessage uMessage) {
                super.launchApp(context, uMessage);
                remindCar(uMessage);
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
                remindCar(uMessage);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
    }

    private void remindCar(UMessage msg) {
        Map<String, String> notifyMap = new HashMap<>();
        for (Map.Entry<String, String> entry : msg.extra.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            notifyMap.put(key, value);
        }
        if (notifyMap.get("type").equals("remindCar")) {
            //以下页面在前台，点击有车提醒通知不跳转
            if (isForeground(mContext)) {

            } else {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("notifyMap", (Serializable) notifyMap);
                intent.putExtra("remindCar", true);
                intent.setClass(mContext, MainActivity.class);
                startActivity(intent);
            }
        }
    }


    //判断页面是否在前台,在前台不跳转
    private boolean isForeground(Context context) {
        if (context == null) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (cpn.getClassName().equals("com.yingjia.chuxing.activity.PostActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.PaymentActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.PayDetailActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.DrivingActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.BikeInUseActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.BikeInRidingActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.BikeSettlementDetailActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.BikeRedTaskActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.LoginActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.SplashActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.GuideActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.ChooseCouponsActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.QualificationActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.RepairBTBikeActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.BikeCertificateActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.NavigationActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.activity.FestivalActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.wxapi.WXEntryActivity") ||
                    cpn.getClassName().equals("com.yingjia.chuxing.wxapi.WXPayEntryActivity") ||
                    cpn.getClassName().equals("com.umeng.qq.tencent.AuthActivity") ||
                    cpn.getClassName().equals("com.umeng.qq.tencent.AssistActivity")
                    ) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(mContext);
    }

    public String getUid() {
        if (uid == null || uid.equals("")) {
            uid = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_ID);
        }
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.USER_ID, uid);
    }

    public String getToken() {
        if (token == null || token.equals("")) {
            token = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_TOKEN);
        }
        return token;
    }

    public void setToken(String token) {
        this.token = token;
        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.USER_TOKEN, token);
    }

    public String getAppVersion() {
        if (appVersion == null || appVersion.equals("")) {
            verControl = new VerControlUtils(mContext);
            appVersion = verControl.getVersionName();
        }
        return appVersion;
    }

    public String getSdkVersion() {
        return SDK;
    }

    public String getImageUrl() {
        if (imageUrl == null || imageUrl.equals("")) {
            imageUrl = SharedPreferencesUtils.getInstance(mContext).getStringValue("imageUrl");
        }
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
        SharedPreferencesUtils.getInstance(mContext).putStringValue("imageUrl", imageUrl);
    }

    public String getHotLine() {
        if (hotLine == null || hotLine.equals("")) {
            hotLine = SharedPreferencesUtils.getInstance(mContext).getStringValue("hotLine");
        }
        return hotLine;
    }

    public void setHotLine(String hotLine) {
        this.hotLine = hotLine;
        SharedPreferencesUtils.getInstance(mContext).putStringValue("hotLine", hotLine);
    }

    public String getTimestamp() {
        String timestamp = new Date().getTime() + "";
        try {
            sign = Md5Utils.getMD5String(timestamp + "incar1"); //时间戳+yingjia+1(平台)
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return timestamp;
    }

    public String getSign() {
        return sign;
    }

    public String getAreaCode() {
        if (areaCode == null || areaCode.equals("")) {
            areaCode = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.AREA_CODE);
        }
        return areaCode;
    }

    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.AREA_CODE, areaCode);
    }

    public String getAdCode() {
        if (adCode == null || adCode.equals("")) {
            adCode = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.AD_CODE);
        }
        return adCode;
    }

    public void setAdCode(String adCode) {
        this.adCode = adCode;
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue(SharedPreferencesKey.AD_CODE, adCode);
    }

    public void setCurPosition(String latitude, String longitude) {
        if (!"".equals(latitude) && latitude != null) {
            curPosition[0] = latitude;
            curPosition[1] = longitude;
            SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue(SharedPreferencesKey.CUR_POSITION, latitude + "," + longitude);
        }
    }

    public String[] getCurPosition() {
        if (curPosition[0] == null || "".equals(curPosition[0])) {
            String savedCurPosition = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.CUR_POSITION);
            if (savedCurPosition != null) {
                curPosition = savedCurPosition.split(",");
            }
        }
        return curPosition;
    }

    public int getTripMode() {
        if (tripMode == 0) {
            tripMode = SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.TRIP_MODE);
        }
        return tripMode;
    }

    public void setTripMode(int tripMode) {
        this.tripMode = tripMode;
        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.TRIP_MODE, tripMode);
    }

    public int getTripAvai() {
        if (tripAvai == 0) {
            tripAvai = SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.TRIP_AVAI);
        }
        return tripAvai;
    }

    public void setTripAvai(int tripAvai) {
        this.tripAvai = tripAvai;
        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.TRIP_AVAI, tripAvai);
    }

    public byte[] getBtToken() {
        if (btToken == null) {
            String btTokenStr = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.BT_TOKEN);
            btToken = new byte[4];
            if (btTokenStr != null) {
                String[] btTokenStrs = btTokenStr.split(",");
                for (int i = 0; i < btTokenStrs.length; i++) {
                    btToken[i] = Byte.parseByte(btTokenStrs[i]);
                }
            }
        }
        return btToken;
    }

    public void setBtToken(byte[] btToken) {
        this.btToken = btToken;
        StringBuilder btTokenStr = new StringBuilder("");
        for (byte tokenSplit : btToken) {
            btTokenStr.append(tokenSplit).append(",");
        }

        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.BT_TOKEN, btTokenStr.toString());
    }

    public String getOrderId() {
        if (orderId == null || adCode.equals("")) {
            orderId = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.ORDER_ID);
        }
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.ORDER_ID, orderId);
    }

    private Map<String, String> requestFieldMap;

    public Map<String, String> getRequestFieldMap() {
        if (requestFieldMap == null) {
            requestFieldMap = new HashMap<>();
        }
        uid = getUid();
        if (uid != null) {
            requestFieldMap.put("userId", uid);
            requestFieldMap.put("uid", uid);
            requestFieldMap.put("token", getToken());
        } else {
            requestFieldMap.remove("userId");
            requestFieldMap.remove("uid");
            requestFieldMap.remove("token");
        }
        areaCode = getAreaCode();
        if (areaCode != null) {
            requestFieldMap.put("areaCode", areaCode);
        }
        adCode = getAdCode();
        if (getAdCode() != null) {
            requestFieldMap.put("adCode", adCode);
        }
        curPosition = getCurPosition();
        if (curPosition != null&&null!=curPosition[0]) {
            requestFieldMap.put("latitude", curPosition[0]);
            requestFieldMap.put("longitude", curPosition[1]);
        }
        requestFieldMap.put("timestamp", getTimestamp());
        requestFieldMap.put("sign", getSign());
        requestFieldMap.put("appVersion", getAppVersion());
        requestFieldMap.put("phoneSysVersion", getSdkVersion());
        requestFieldMap.put("plateForm", "1");
        requestFieldMap.put("platform", "1");
        return requestFieldMap;
    }

}
